<?php
/**
 *
 *  Achachi XML Builder - Framework and applications builder tool
 *  Copyright (C) 2010-2011, Llankay Achachi
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

class expressionEvaluator {
  protected $vars;
  function replace_all($__match__)
  {
    if($__match__[1]=='@') return $this->replace(array(1=>$__match__[2]));
    if($__match__[1]=='$') return $this->replace_exp(array(1=>$__match__[2]));
    if($__match__[1]=='#') return $this->replace_exec(array(1=>$__match__[2]));
  }
  function replace($__match__)
  {
    global $PARAMS;
    foreach($this->vars as $___ => &$____) $$___ = $____;
    return eval("return {$__match__[1]};");
  }
  function replace_exp($__match__)
  {
    global $PARAMS;
    foreach($this->vars as $___ => &$____) $$___ = $____;
    return var_export(eval("return {$__match__[1]};"),true);
  }
  function replace_exec($__match__)
  {
    global $PARAMS;
    foreach($this->vars as $___ => &$____) $$___ = $____;
    return eval($__match__[1]);
  }
  function evaluate($exp,$vars=null)
  {
    if($vars) {$prevars = $this->vars; $this->vars = $vars;} else {$prevars = false;}
    //Bug Fix: No se pueden usar $\{}
    $res = preg_replace_callback('/(@|\$|#)\{([^\}]+)\}/', array($this,'replace_all'), $exp);
    $res = preg_replace('/#\\\{/', '#{', $res);
    $res = preg_replace('/@\\\{/', '@{', $res);
    $res = preg_replace('/\$\\\{/', '${', $res);
    if($prevars) $this->vars = $prevars;
    return $res;
  }
  static function evaluateS($exp,$vars){
    $ee = new expressionEvaluator();
    return $ee->evaluate($exp,$vars);
  }
}